package com.zcf.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zcf.common.json.Body;
import com.zcf.gameController.WebSocketBull;
import com.zcf.gameController.gameUtils.gameLogic;
import com.zcf.mapper.RoomMapper;
import com.zcf.mapper.RoomParamMapper;
import com.zcf.mapper.RoomRecordMapper;
import com.zcf.pojo.Room;
import com.zcf.pojo.RoomParam;
import com.zcf.pojo.RoomRecord;
import com.zcf.pojo.User;
import com.zcf.vo.out.LayuiJson;
import com.zcf.vo.out.recordOut;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.chainsaw.Main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZhaoQi
 * @since 2019-03-18
 */
@Service
public class RoomRecordServiceImpl  {

	@Autowired
	RoomRecordMapper rrm;
	@Autowired
	RoomParamMapper rp;

	/**
	 * 后端获取战绩
	 * @param record
	 * @return
	 */
	public LayuiJson getrecord(RoomRecord record,int pagenum,int pagesize) {
		LayuiJson lj = new LayuiJson();
		int count;
		EntityWrapper<RoomRecord> w = new EntityWrapper<RoomRecord>();
		if (record.getRoomNum()!=null && record.getRoomNum()!=""){//获取指定房间
			w.eq("roomNum",record.getRoomNum());
			w.setSqlSelect("roomNum","points","createTime","gameType","roomType");
		}else if(record.getGameId()==null){
			w.setSqlSelect(" roomNum","points","createTime","gameType","roomType");
		}

		if(record.getGameId() != null &&record.getRoomNum()!=null && record.getRoomNum()!="" ){
			w.eq("roomNum",record.getRoomNum());
			w.setSqlSelect("roomNum","points","winNumber","gameId","phone","username","uid","userCards","cardType","createTime","gameType","roomType");

		}
		if(record.getGameId() == null){
			count = rrm.selectcount();
			w.groupBy("roomNum");
		}else{
			count = record.selectCount(new EntityWrapper<RoomRecord>().eq("roomNum", record.getRoomNum()));
		}
		w.orderBy("createTime",false);
		List<RoomRecord> list = rrm.selectPage(new Page<>(pagenum, pagesize), w);
		if (list == null || list.size()==0) {
			lj.setCode(1);
			lj.setMsg("无数据");
			lj.setCount(0);
			lj.setData(null);
			return lj;
		}
		lj.setCode(0);
		lj.setMsg("yes");
		lj.setCount(count);
		lj.setData(list);
		return lj;

	}
	/**
	 * 获取战绩详情
	 * @param record
	 * @return
	 */
	public Body getRecordInfo(RoomRecord record) {
		List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
		if(record.getRoomNum() != "" && record.getRoomNum() != null){
			Map<String, Object> map;
			//根据房间号 用户id 获取战绩
			List<RoomRecord> list = record.selectList(new EntityWrapper<RoomRecord>().eq("roomNum", record.getRoomNum()).eq("uid", record.getUid()).setSqlSelect("gameId","createTime","num"));
			if(list.size()!=0){
				for (RoomRecord roomRecord : list) {
					map = new HashMap<String, Object>();
					map.put("gameId", roomRecord.getGameId());
					map.put("createTime", gameLogic.gettime(roomRecord.getCreateTime().getTime()));
					map.put("winNumber", roomRecord.getWinNumber());
					list1.add(map);
				}
			}

		}
		if(list1!=null)return Body.newInstance(list1);
		return Body.BODY_401;

	}


	public void insert(RoomRecord ri) {
		rrm.insert(ri);
	}
	/**
	 * 外围获取战绩
	 * @param record
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public Body getrecords(RoomRecord record, int userid,int type) {
		List<Map<String,Object >> list1 = new ArrayList<Map<String,Object >>();
		Map<String,Object > map = null ;
		List<recordOut> list = rrm.selectRoom(String.valueOf(userid));//通过用户id获取参与的房间
		for (recordOut re : list) {
			//			RoomParam param = new RoomParam();
			//			List<RoomParam> selectList = param.selectList(new EntityWrapper<RoomParam>().eq("roomId", re.getRoomNum()));
			//			if(selectList.size()!=0){
			//				for (RoomParam roomParam : selectList) {
			if(type == 0){//0 普通模式 1 俱乐部模式
				// roomType 0 牛牛 1 扎金花  gameType 0 普通模式 1 俱乐部模式
				if(re.getRoomType() == record.getRoomType() && re.getGameType() == record.getGameType()){
					map = new HashMap<>();

					map.put("roomName", re.getRoomNum());
					map.put("num", rrm.selectmaxgameid(userid+"", re.getRoomNum())+"/"+re.getNum());
					map.put("points", re.getPoints());
					map.put("createTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(re.getCreateTime().getTime())));
					map.put("users",recordoverview(re.getRoomNum()));
					list1.add(map);
				}
			}else if(type == 1){//0 普通模式 1 俱乐部模式
				if(re.getRoomType() == record.getRoomType()){
					map = new HashMap<>();
					map.put("roomName", re.getRoomNum());
					map.put("num", rrm.selectmaxgameid(userid+"", re.getRoomNum())+"/"+re.getNum());
					map.put("points", re.getPoints());
					map.put("createTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(re.getCreateTime().getTime())));
					map.put("users",recordoverview(re.getRoomNum()));
					list1.add(map);
				}
			}


			//					map.put("gameType", roomParam.getGameType());

			//					if(roomParam.getGameType() == 1){
			//						map.put("integral",rrm.selectsumnum(String.valueOf(userid),String.valueOf(roomParam.getRoomId())));
			//					}else{
			//						map.put("integral", re.getWinNumber());
			//					}

		}
		//			}
		//		}
		if(list1!=null){
			return Body.newInstance(list1);
		}
		return Body.BODY_401;
	}

	/**
	 * 外围获取战绩总览
	 * @param string
	 * @return
	 */
	public List<Map<String, Object>> recordoverview(String roomName) {
		List<Map<String, Object>> lists = new ArrayList<Map<String,Object>>();
		RoomRecord record = new RoomRecord();
		if( roomName!=null){
			Map<String, Object> map ;
			List<RoomRecord> list = record.selectList(new EntityWrapper<RoomRecord>().eq("roomNum", roomName).setSqlSelect("uid","userimg","username","money").groupBy("uid"));
			if(list.size()!=0){
				for (RoomRecord roomRecord : list) {
					map = new HashMap<String, Object>();
					map.put("id", roomRecord.getUid());
					map.put("userName", roomRecord.getUsername());
					map.put("userImg", roomRecord.getUserimg());
					map.put("money", roomRecord.getMoney());
					map.put("integral",rrm.selectsumnum(String.valueOf(roomRecord.getUid()),String.valueOf(roomName)));
					//					list1.add(rrm.selectsumnum(String.valueOf(roomRecord.getUid()),String.valueOf(roomName)));
					lists.add(map);
				}
				for (int i = 0; i < lists.size(); i++) {
					Collections.sort( lists ,new Comparator<Map<String, Object>>() {
						@Override
						public int compare(Map<String, Object> o1, Map<String, Object> o2) {
							int io1 =(int) o1.get("integral");
							int io2 = (int) o2.get("integral");
							return io2-io1;
						}
					});
				}
				return lists;
			}
		}
		return null;
	}
	/**
	 * 获取对局详情
	 * @param record
	 * @return
	 */

	public Body getnuminfo(RoomRecord record) {
		List<Map<String, Object>> lists = new ArrayList<Map<String,Object>>();
		List<Integer> list1 = new ArrayList<Integer>();
		Map<String, Object> map ;
		if(record.getGameId() != null && record.getRoomNum() !=""){
			List<RoomRecord> list = record.selectList(new EntityWrapper<RoomRecord>().eq("roomNum", record.getRoomNum()).eq("gameId", record.getGameId()).setSqlSelect("uid","userimg","username","userCards","winNumber","createTime"));
			if(list.size()!=0){
				for (RoomRecord roomRecord : list) {
					map = new HashMap<String, Object>();
					map.put("id", roomRecord.getUid());
					map.put("userName", roomRecord.getUsername());
					map.put("userImg", roomRecord.getUserimg());
					//					map.put("integral",rrm.selectsumnum(String.valueOf(roomRecord.getUid()),String.valueOf(record.getRoomNum())));
					map.put("integral",roomRecord.getMoney());
					map.put("userCards", roomRecord.getUserCards().split(","));
					map.put("createTime", gameLogic.gettime(roomRecord.getCreateTime().getTime()));
					list1.add(rrm.selectsumnum(String.valueOf(roomRecord.getUid()),String.valueOf(record.getRoomNum())));
					lists.add(map);
				}
				Integer[] integers = BubbleSort(list1);
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("winner",integers[0]);
				map1.put("users", lists);
				if(map1!=null)return Body.newInstance(map1);
			}
		}
		return Body.BODY_401;
	}
	/**
	 * 集合转数组从大到小冒泡排序
	 * @param list1
	 * @return
	 */
	public Integer[] BubbleSort(List<Integer> list1){
		Integer[] integrals = new Integer[list1.size()];
		Integer[] integers = list1.toArray(integrals);
		for (int i = 0; i < integers.length-1; i++) {
			for (int j = 0; j < integers.length-1-i; j++) {
				if(integers[j]<integers[j+1]){
					int temp=integers[j+1];
					integers[j+1]=integers[j];
					integers[j]=temp;
				}
			}
		}
		return integers;
	}

	public static void timer4() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 20); // 控制时
		calendar.set(Calendar.MINUTE, 05);    // 控制分
		calendar.set(Calendar.SECOND, 0);    // 控制秒

		Date time = calendar.getTime();     // 得出执行任务的时间,此处为今天的12：00：00

		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				System.out.println("-------设定要指定任务--------");
				//				rrm.delrecord();

			}
		}, time, 1000 * 60 * 60 * 24);// 这里设定将延时每天固定执行
	}


}


